import logging
from pylons.controllers.util import abort, redirect_to
from pylons import request, response, session, tmpl_context as c
from hellopylons.lib.base import BaseController, render
from hellopylons.model import meta
from hellopylons.model import User


from beaker import session

log = logging.getLogger(__name__)

class CustomMiddleware(object):
    def __init__(self, app):
        self.app = app
        
    def __call__(self, environ, start_response):
        excludeAction = {
                         'User': ['Login', 'Register', 'RegOver']
                         }
        #print(environ)
        session = environ['beaker.session']
        routing_args = environ['wsgiorg.routing_args']
        #print(routing_args[1])
        strController = ''
        strAction = ''
        if 'controller' in routing_args[1]:
            strController = routing_args[1]['controller']
        if 'action' in routing_args[1]:
            strAction = routing_args[1]['action']
        print(environ['wsgi.input'])
        if strController in excludeAction and strAction in excludeAction[strController]:
            #print(environ['QUERY_STRING'])
            return self.app(environ, start_response)
        else:
            if 'LoginUser' in session:
                #print(session['preUrl'])
                return self.app(environ, start_response)
            else:
                pathInfo = environ['PATH_INFO']
                queryString = environ['QUERY_STRING']
                preURL = pathInfo
                if queryString != '':
                    preURL = ''.join([pathInfo, '?', queryString])
                session['preUrl'] = preURL
                routing_args[1]['controller'] = 'User'
                routing_args[1]['action'] = 'Index'
        #print(environ["HTTP_ACCEPT_LANGUAGE"])
        return self.app(environ, start_response)
    
    
    